<template>
  <div style="padding-left: 20px; padding-right: 20px; padding-top: 20px">
    <el-card class="box-card" shadow="never">
      <div slot="header" class="clearfix">
        <header-toolbar :buttons="headerButtons" @delete="handleDelete" @refresh="handleRefresh" @save="handleSave"
          :objectId.sync="order.id" @submit="handleSubmit" @back="handleReturnList" @approve="handleApprove"
          @print="handlePrint" @unsubmit="handleUnSubmit" @pushButtonClick="handlePushClick"
          :status.sync="order.status">
          <template v-slot:pushButton>
            <el-dropdown-item command="pushAdvancePaymentRequisition" icon="el-icon-download">预付申请</el-dropdown-item>
            <el-dropdown-item command="pushPurchaseReceipt" icon="el-icon-download">采购入库</el-dropdown-item>
          </template>
        </header-toolbar>
      </div>
      <div class="text item">
        <el-form :model="order" :rules="headerRules" ref="orderForm" label-width="100px" label-position="rigth">
          <el-row>
            <el-col :span="6">
              <el-form-item label="单据编号" prop="number">
                <el-input v-model="order.number" disabled :placeholder="order.id ? '' : '保存后自动生成'"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="类型" prop="type">
                <el-select v-model="order.type" placeholder="请选择类型" :disabled="readonly" style="width: 100%;"
                  @change="handleChangeProductType">
                  <el-option :value="1" label="标准采购"></el-option>
                  <el-option :value="2" label="直运采购"></el-option>
                  <el-option :value="3" label="费用采购"></el-option>
                  <el-option :value="4" label="资产采购"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="供应商" prop="status">
                <supplier-select v-model="order.supplierId" @change="handleSupplierChange" :disabled="readonly">
                </supplier-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="订单日期" prop="date">
                <el-date-picker v-model="order.date" type="date" placeholder="选择日期" :disabled="readonly">
                </el-date-picker>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="要货日期" prop="requiredDate">
                <el-date-picker v-model="order.requiredDate" type="date" placeholder="选择日期" :disabled="readonly">
                </el-date-picker>
              </el-form-item>
            </el-col>


          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="币别" prop="currencyId">
                <currency-select v-model="order.currencyId" placeholder="请选择币别" :disabled="readonly"
                  @change="handleChangeCurrency">
                </currency-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="汇率" prop="exchangeRate">
                <number-input v-model="order.exchangeRate" :precision="6" :min="0" controls-position="right"
                  style="width: 100%;" :disabled="readonly" @change="handleChangeExchangeRate"></number-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="采购部门" prop="departmentId">
                <department-select v-model="order.departmentId" @change="() => order.purchaserId = null"
                  :disabled="readonly">
                </department-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="采购员" prop="purchaserId">
                <employee-select v-model="order.purchaserId" :departmentId.sync="order.departmentId"
                  :disabled.sync="!order.departmentId" :disabled="readonly">
                </employee-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="含税" prop="includeTax">
                <el-checkbox v-model="order.includeTax" :disabled="readonly" @change="handleChangeIncludeTax">
                </el-checkbox>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="合计金额" prop="totalAmountFr">
                <el-input v-model="order.totalAmountFr" disabled>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="备注" prop="comment">
                <el-input v-model="order.comment" :disabled="readonly"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="单据状态" prop="status">
                <status-label :status.sync="order.status">
                </status-label>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>
    <el-divider></el-divider>
    <el-card class="box-card" shadow="never">
      <div slot="header" class="clearfix">
        <body-toolbar :table="$refs.xTable" @add="handleAddItem" @delete="handleBodyDelete" @fill="handleFill"
          :status.sync="order.status"></body-toolbar>
      </div>
      <div class="text item">
        <vxe-table border align="center" show-footer :data="order.items" auto-resize :export-config="{}" resizable
          ref="xTable" :show-overflow="true" @cell-click="handleCellClick" size="small" :edit-rules="bodyRules"
          :mouse-config="{ selected: true }" :checkbox-config="{ range: true }" :keyboard-config="{
            isArrow: true,
            isDel: false,
            isEnter: true,
            isTab: true,
            isEdit: true,
          }" :edit-config="{
            trigger: 'click',
            mode: 'cell',
            activeMethod: handleCellEnableEdit,
          }" :footer-method="handleFooterData" :merge-footer-items="mergeFooterItems">
          <vxe-table-column type="checkbox" width="40" fixed="left"></vxe-table-column>
          <vxe-table-column type="seq" width="40" fixed="left"></vxe-table-column>
          <vxe-table-column field="productCode" title="产品代码" align="left" header-align="center" width="120" fixed="left"
            :edit-render="{
              attrs: {},
              enabled: !this.readonly,
            }">
            <template #default="{ row }">
              <div>
                {{ row.productCode }}
              </div>
            </template>
            <template #edit="{ row }">
              <product-select v-model="row.productId"
                @change="(product) => handleChangeProduct(row, product)"></product-select>
            </template>
          </vxe-table-column>
          <vxe-table-column field="productName" title="产品名称" align="left" header-align="center" width="140"
            fixed="left">
            <template #default="{ row }">
              <div>
                {{ row.productName }}
              </div>
            </template>
          </vxe-table-column>
          <vxe-table-column field="productModel" title="规格型号" align="left" header-align="center" width="120"
            fixed="left">
            <template #default="{ row }">
              <div>
                {{ row.productModel }}
              </div>
            </template>
          </vxe-table-column>
          <vxe-table-column field="remark" title="备注" align="left" header-align="center" width="120" :edit-render="{
            attrs: {},
            enabled: !this.readonly,
          }">
            <template #default="{ row }">
              <div>
                <span>{{ row.remark }}</span>
              </div>
            </template>
            <template #edit="{ row }">
              <el-input v-model="row.remark"></el-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="isGift" title="赠品" align="left" header-align="center" width="120" :edit-render="{
            attrs: {},
            enabled: !this.readonly,
          }">
            <template #default="{ row }">
              <div>
                <span>{{ row.isGift ? "是" : "" }}</span>
              </div>
            </template>
            <template #edit="{ row }">
              <el-select v-model="row.isGift">
                <el-option :value="true" label="是"></el-option>
                <el-option :value="false" label="否"></el-option>
              </el-select>
            </template>
          </vxe-table-column>
          <vxe-table-column field="purchaseUnitId" title="采购单位" align="center" header-align="center" width="120"
            :edit-render="{
              attrs: {},
              autofocus: '.custom-input',
              enabled: !this.readonly,
            }">
            <template #default="{ row }">
              <div>
                {{ row.purchaseUnitName }}
              </div>
            </template>
            <template #edit="{ row }">
              <unit-select v-model="row.purchaseUnitId" @change="(unit) => handleUnitChange(row, unit)"></unit-select>
            </template>
          </vxe-table-column>

          <vxe-table-column field="purchaseQuantity" title="采购数量" align="right" header-align="center" width="120"
            :edit-render="{
              attrs: {},
              autofocus: '.custom-input',
              enabled: !this.readonly,
            }">
            <template #default="{ row }">
              <div>
                {{ row.purchaseQuantity }}
              </div>
            </template>
            <template #edit="{ row }">
              <number-input v-model="row.purchaseQuantity" :precision="4" optionClass="vxe-table–ignore-clear"
                @input="(quantity) => handleQuanityChange(row, quantity)"></number-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="basicUnitId" title="计价单位" align="center" header-align="center" width="120"
            :edit-render="{
              attrs: {},
              autofocus: '.custom-input',
              enabled: false,
            }">
            <template #default="{ row }">
              <div>
                {{ row.basicUnitName }}
              </div>
            </template>
          </vxe-table-column>

          <vxe-table-column field="basicQuantity" title="计价数量" align="right" header-align="center" width="120"
            :edit-render="{
              attrs: {},
              autofocus: '.custom-input',
              enabled: false,
            }">
            <template #default="{ row }">
              <div>
                {{ row.basicQuantity }}
              </div>
            </template>
          </vxe-table-column>
          <vxe-table-column field="price" title="单价" align="right" header-align="center" width="120" :edit-render="{
            attrs: {},
            enabled: !this.readonly,
          }">
            <template #default="{ row }">
              <div>
                <span>{{ row.price }}</span>
              </div>
            </template>
            <template #edit="{ row }">
              <number-input v-model="row.price" :precision="4" :min="0"
                @input="(price) => handleChangePrice(row, price)"></number-input>
            </template>
          </vxe-table-column>
          <vxe-table-column field="taxRateId" title="税率" align="left" header-align="center" width="120" :edit-render="{
            attrs: {},
          }">
            <template #default="{ row }">
              <div>
                <span>{{ row.taxRateName }}</span>
              </div>
            </template>
            <template #edit="{ row }">
              <taxrate-select v-model="row.taxRateId"
                @change="(taxRate) => handleChangeTaxRate(row, taxRate)"></taxrate-select>
            </template>
          </vxe-table-column>
          <vxe-table-column field="priceIncludeTax" title="含税单价" align="right" header-align="center" width="120"
            :edit-render="{
              attrs: {},
            }">
            <template #default="{ row }">
              <div>
                <span>{{ row.priceIncludeTax }}</span>
              </div>
            </template>
          </vxe-table-column>
          <vxe-table-column field="priceExcludeTax" title="不含税单价" align="right" header-align="center" width="120"
            :edit-render="{
              attrs: {},
              enabled: false
            }">
            <template #default="{ row }">
              <div>
                <span>{{ row.priceExcludeTax | money }}</span>
              </div>
            </template>
          </vxe-table-column>

          <vxe-table-column field="amountFr" title="不含税金额" align="right" header-align="center" width="120" :edit-render="{
            attrs: {},
            enabled: false
          }">
            <template #default="{ row }">
              <div>
                <span>{{ row.amountFr | money }}</span>
              </div>
            </template>
          </vxe-table-column>
          <vxe-table-column field="amountFr" title="税额" align="right" header-align="center" width="120" :edit-render="{
            attrs: {},
            enabled: false
          }">
            <template #default="{ row }">
              <div>
                <span>{{ row.taxAmountFr | money }}</span>
              </div>
            </template>
          </vxe-table-column>
          <vxe-table-column field="amountFr" title="价税合计" align="right" header-align="center" width="120" :edit-render="{
            attrs: {},
            enabled: false
          }">
            <template #default="{ row }">
              <div>
                <span>{{ row.totalAmountFr | money }}</span>
              </div>
            </template>
          </vxe-table-column>
        </vxe-table>
      </div>
    </el-card>
    <el-divider></el-divider>
    <el-card class="box-card" shadow="never">
      <div slot="header" class="clearfix">
        <body-toolbar :table="$refs.xTable" @add="handleAddAdvanceItem" @delete="handleDeleteAdvanceItem"
          :buttons="advanceButtons"></body-toolbar>
      </div>
      <div class="text item">
        <vxe-table border align="center" show-footer :data="order.advancePaymentItems" auto-resize :export-config="{}"
          resizable ref="advanceTable" :show-overflow="true" @cell-click="handleAdvanceCellClick" size="small"
          :mouse-config="{ selected: true }" :checkbox-config="{ range: true }" :keyboard-config="{
            isArrow: true,
            isDel: false,
            isEnter: true,
            isTab: true,
            isEdit: true,
          }" :edit-config="{
            trigger: 'click',
            mode: 'cell',
            activeMethod: handleAdvanceCellEnableEdit,
          }" :footer-method="handleAdvanceFooterData" :merge-footer-items="mergeFooterItems">
          <vxe-table-column type="checkbox" width="40" fixed="left"></vxe-table-column>
          <vxe-table-column type="seq" width="40" fixed="left"></vxe-table-column>
          <vxe-table-column field="advancePaymentPercent" title="预付比例" align="right" header-align="center" width="120"
            :edit-render="{
              attrs: {},
              enabled: !this.readonly,
            }">
            <template #default="{ row }">
              <div>
                {{ row.advancePaymentPercent ? row.advancePaymentPercent + "%" : "" }}
              </div>
            </template>
            <template #edit="{ row }">
              <number-input v-model="row.advancePaymentPercent" @input="() => handleChangePercent(row)"></number-input>
            </template>

          </vxe-table-column>
          <vxe-table-column field="advancePaymentAmountFr" title="预付金额" align="right" header-align="center" width="140"
            :edit-render="{
              attrs: {},
              enabled: false,
            }">
            <template #default="{ row }">
              <div>
                {{ row.advancePaymentAmountFr | money }}
              </div>
            </template>
          </vxe-table-column>
          <vxe-table-column field="dueDate" title="到期日" align="left" header-align="center" width="140" :edit-render="{
            attrs: {},
            enabled: !this.readonly,
          }">
            <template #default="{ row }">
              <div>
                {{ row.dueDate | date }}
              </div>
            </template>
            <template #edit="{ row }">
              <el-date-picker v-model="row.dueDate" type="date" :picker-options="pickerOptions"
                popper-class="vxe-table–ignore-clear" format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
            </template>
          </vxe-table-column>
          <vxe-table-column field="expectedDate" title="期望付款日期" align="left" header-align="center" width="140"
            :edit-render="{
              attrs: {},
              enabled: !this.readonly,
            }">
            <template #default="{ row }">
              <div>
                {{ row.expectedDate | date }}
              </div>
            </template>
            <template #edit="{ row }">
              <el-date-picker v-model="row.expectedDate" type="date" :picker-options="pickerOptions"
                popper-class="vxe-table–ignore-clear" format="yyyy-MM-dd" value-format="yyyy-MM-dd"></el-date-picker>
            </template>
          </vxe-table-column>
          <vxe-table-column field="advancePaymentNumber" title="预付单号" align="left" header-align="center" width="120">
            <template #default="{ row }">
              <div>
                {{ row.AdvancePaymentNumber }}
              </div>
            </template>
          </vxe-table-column>
          <vxe-table-column field="paymentAmountFr" title="付款金额" align="left" header-align="center" width="120">
            <template #default="{ row }">
              <div>
                {{ row.AdvancePaymentNumber }}
              </div>
            </template>
          </vxe-table-column>
        </vxe-table>
      </div>
    </el-card>
    <el-drawer direction="rtl" :visible.sync="editAttachmentDrawer" :with-header="false">
      <div v-if="editAttachmentDrawer">
        <attachment-panel :moduleCode="'purchaseOrder'" :ownerId="order.id"></attachment-panel>
      </div>
    </el-drawer>
    <print-dialog ref="printPanel" :moduleCode="'purchaseOrder'" :ids="[this.id]"></print-dialog>
  </div>
</template>
<script>
import {
  getOrder,
  addOrder,
  updateOrder,
  deleteOrder,
  updateOrderStatus,
  pushReceipt,
  pushPaymentRequisition
} from "@/api/purchase/order";

import { getProductPurchase } from "@/api/product"
import { calculateAmount, calculateBasicQuantity, setUnitConversionRate, setProductLatestPrice } from "@/utils/document"
import headerToolbar from "@/components/Bar/documentHeaderToolbar.vue";
import bodyToolbar from "@/components/Bar/documentBodyToolbar.vue";
import currencySelect from "@/components/Select/currencySelect.vue";
import departmentSelect from "@/components/Select/departmentSelect.vue";
import employeeSelect from "@/components/Select/employeeSelect.vue";
import supplierSelect from "@/components/Select/supplierSelect.vue";
import attachmentPanel from "@/components/Attachment/index.vue";
import printDialog from "@/components/Print/index.vue";
import unitSelect from "@/components/Select/unitSelect.vue";
import taxrateSelect from "@/components/Select/taxrateSelect.vue";
import numberInput from "@/components/Input/numberInput.vue";
import statusLabel from "@/components/Label/documentStatusLabel.vue";
import productSelect from "@/components/Select/productSelect.vue";
export default {
  components: {
    headerToolbar,
    bodyToolbar,
    currencySelect,
    departmentSelect,
    employeeSelect,
    unitSelect,
    supplierSelect,
    attachmentPanel,
    printDialog,
    taxrateSelect,
    numberInput,
    statusLabel,
    productSelect,
  },
  data() {
    return {
      order: {
        id: null,
        number: null,
        type: 1,
        supplierId: null,
        date: null,
        requiredDate: null,
        includeTax: true,
        currencyId: null,
        exchangeRate: null,
        totalAmountFr: null,
        comment: null,
        purchaserId: null,
        departmentId: null,
        status: 1,
        items: [],
        advancePaymentItems: []
      },
      headerRules: {
        date: [
          {
            required: true,
            message: "请选择日期",
            trigger: "change",
          },
        ],
        type: [
          {
            required: true,
            message: "请选择类型",
            trigger: "change",
          },
        ],
        supplierId: [
          {
            required: true,
            message: "请选择供应商",
            trigger: "change",
          },
        ],
        currencyId: [
          {
            required: true,
            message: "请选择币别",
            trigger: "change",
          },
        ],
        exchangeRate: [
          {
            required: true,
            message: "请填写汇率",
            trigger: "change",
          },
        ]
      },
      bodyRules: {
        productId: [{ required: true, message: "请选择产品" }],
        purchaseUnitId: [{ required: true, message: "请填写采购单位" }],
        purchaseQuantity: [{ required: true, message: "请填写采购数量" }],
      },
      isModifying: false,
      mergeFooterItems: [{ row: 1, col: 2, rowspan: 1, colspan: 6 }],
      editAttachmentDrawer: false,
      currentCell: { row: null, column: null },
      quantityField: "purchaseQuantity",
      auxiliaryUnitField: "purchaseUnitId",
      headerButtons: ['save', 'submit', 'unsubmit', 'delete', 'back', 'approve', 'unapprove', 'print', 'push'],
      advanceButtons: ["add", "remove"],
      pickerOptions: {
        cellClassName: "vxe-table–ignore-clear"
      }
    };
  },
  methods: {
    getData() {
      if (!this.id) {
        this.setDefaultInfo();
        return;
      }
      getOrder(this.id).then((res) => {
        this.order = res || {};
      });
    },
    handleRefresh() {
      this.getData();
    },
    handleReturnList() {
      if (this.isModifying) {
        this.$confirm("当前数据为保存，是返回列表?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.$router.push({
              name: "PurchaseOrder",
            });
          })
          .catch(() => { });
      } else {
        this.$router.push({
          name: "PurchaseOrder",
        });
      }
    },
    handleAddItem() {
      let item = this.getDefaultItemValue();

      this.$refs.xTable.insertAt(item, -1);
      this.order.items.push(item);
    },
    handleDelete({ id }) {
      deleteOrder(id).then((res) => {
        this.$notify({
          title: "成功",
          message: "删除成功",
          type: "success",
          position: "bottom-right",
        });
        this.isModifying = false;
        this.handleReturnList();
      });
    },
    handleApprove(approved) {
      let status = approved ? 4 : 2;

      this.changeStatus(status)
    },
    handleSave() {
      this.validate(() => {
        this.saveData();
      })
    },
    handleSubmit() {
      this.changeStatus(3)
    },
    handleUnSubmit() {
      this.changeStatus(2)
    },
    async validate(callback) {
      const v1 = new Promise((resolve, reject) => {
        this.$refs.orderForm.validate(valid => {
          if (valid) resolve();
        }, true);
      });

      const v2 = new Promise((resolve, reject) => {
        this.$refs.xTable.validate(true, (errMap) => {
          if (errMap) {
            reject();
          } else {
            resolve();
          }
        });
      });

      Promise.all([v1, v2]).then(() => {
        callback(true);
      });
    },
    saveData() {
      let items = this.getValidItems();

      this.order.items = items;
      if (this.id) {
        updateOrder(this.order).then((res) => {
          if (res) {
            this.order = res;
            this.$notify({
              title: "成功",
              message: "保存成功",
              type: "success",
              position: "bottom-right",
            });
          }
        });
      } else {
        addOrder(this.order).then((res) => {
          if (res) {
            this.order = res;
            this.$notify({
              title: "成功",
              message: "保存成功",
              type: "success",
              position: "bottom-right",
            });
          }
        });
      }
    },
    changeStatus(status) {
      updateOrderStatus(this.order.id, status).then(res => {
        let message = "";
        if (status == 3)
          message = "提交成功";
        else if (status == 2 && this.order.status == 3)
          message = "撤销提交成功";
        else if (status == 3 && this.order.status == 4)
          message = "反审核成功";

        this.$notify({
          title: "成功",
          message: message,
          type: "success",
          position: "bottom-right",
        });
        this.getData();
      })
    },
    getValidItems() {
      let items = this.order.items.filter(x => x.productId);

      if (!items)
        return [];

      for (let i = 0; i < items.length; i++) {
        items[i].index = i + 1;
      }
      return items;
    },
    handleCellEnableEdit({ row, rowIndex, column, columnIndex }) {
      return true;
    },
    handleCellClick({ row, rowIndex, $rowIndex, column, columnIndex, $columnIndex }) {
      this.currentCell = { row: row, column: column }
    },
    getDefaultItemValue() {
      return {
        id: null,
        remark: null,
        productId: null,
        productCode: null,
        productName: null,
        purchaseUnitId: null,
        purchaseUnitName: null,
        purchaseQuantity: null,
        price: null,
        priceIncludeTax: null,
        priceExcludeTax: null,
        taxRateId: null,
        taxRateName: null,
        taxRateValue: null,
        basicUnitId: null,
        basicUnitName: null,
        basicQuantity: null,
      };
    },
    handleFooterData({ columns, data }) {
      let result = [];

      let subTotalRow = columns.map((column, _columnIndex) => {
        if (_columnIndex === 0) {
          return "";
        }

        if (_columnIndex === 1) {
          return "";
        }
        if (
          ![
            "amountFr",
            "taxAmountFr",
            "totalAmountFr"
          ].includes(column.property)
        ) {
          return "";
        }

        let total = 0;
        data.forEach((item) => {
          if (item[column.property]) total = total + +item[column.property];
        });
        return total.toMoney();
      });

      result.push(subTotalRow);
      return result;
    },
    handleChangeProductType() {
      this.$confirm("更改类型会清空分录行，是否继续", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.order.items = [];
        })
        .catch(() => { });
    },
    handleChangeCurrency(currency) {
      this.order.currencyName = currency.currencyName;
      this.order.exchangeRate = currency.exchangeRate;
      let items = this.order.items;
      if (!items || items.length == 0)
        return;
      items.forEach(item => {
        calculateAmount(this.order.includeTax, this.order.exchangeRate, item, this.quantityField);
      })

    },
    handleChangeExchangeRate(item, value) {
      calculateAmount(this.order.includeTax, item.exchangeRate, item, this.quantityField);
    },
    handleChangeIncludeTax() {
      let items = this.order.items;
      if (!items || items.length == 0)
        return;
      items.forEach(item => {
        calculateAmount(this.order.includeTax, this.order.exchangeRate, item, this.quantityField);
      })
    },
    handleChangeProduct(item, product) {
      if (!product)
        return;
      item.productName = product.name;
      item.productCode = product.code;
      item.productModel = product.model;
      item.basicUnitId = product.basicUnitId;
      item.basicUnitName = product.basicUnitName;

      this.setProductDefaultInfo(item, product.id);
    },
    handleUnitChange(item, unit) {
      item.purchaseUnitName = unit.name;
    },
    handleSupplierChange(supplier) {
      this.order.supplierName = supplier.name;
    },
    handleQuanityChange(item, quantity) {

      calculateBasicQuantity(item, this.quantityField)

      if (!item.productId || !item.basicQuantity || !this.order.currencyId || !this.order.supplierId)
        return;

      setProductLatestPrice(item,
        this.order.currencyId,
        this.order.supplierId,
        this.order.date,
        this.order.includeTax).then(res => {
          calculateAmount(this.order.includeTax, this.order.exchangeRate, item, this.quantityField)
        })
    },
    handleChangeTaxRate(item, taxRate) {
      item.taxRateName = taxRate.name;
      item.taxRateValue = taxRate.rate;
      calculateAmount(this.order.includeTax, item.exchangeRate, item, this.quantity);
    },
    handleChangePrice(item, price) {
      calculateAmount(this.order.includeTax, item.exchangeRate, item, this.quantity);
    },
    setDefaultInfo() {
      this.requisition.date = new Date();
      if (this.order.items && this.order.items.length > 0) return;
      //默认插四行数据
      for (let i = 0; i < 1; i++) {
        let item = this.getDefaultValueItem();
        this.order.items.push(item);
      }
    },
    handleAttachment() {
      this.editAttachmentDrawer = true;
    },
    handlePrint() {
      this.$refs.printPanel.showDialog();
    },
    handleBodyDelete({ ids, rows }) {
      if (rows.length == 0)
        return;

      let xids = rows.map((data) => {
        return data._XID;
      });

      this.order.items = this.order.items.filter((item) => {
        return xids.indexOf(item._XID) < 0
      })
    },
    handleFill() {
      if (!this.currentCell || !this.currentCell.row || this.order.items.length == 0)
        return;
      let row = this.currentCell.row;
      let column = this.currentCell.column;

      //有些字段不允许批量填充
      if (column.property == "productCode") {
        return;
      }

      this.order.items.forEach(item => {
        let columnNames = [column.property];

        if (column.property == "taxRateId") {
          columnNames.push("taxRateName")
        }
        columnNames.forEach(columnName => {
          item[columnName] = row[columnName];
        })

      })
    },
    setProductDefaultInfo(item, productId) {
      getProductPurchase(productId).then(res => {
        if (res) {
          item.purchaseUnitId = res.purchaseUnitId;

          if (item.purchaseUnitId) {
            setUnitConversionRate(item, this.auxiliaryUnitField)
          }

          item.purchaseUnitName = res.purchaseUnitName;
        }
      });
    },
    handlePushClick(command) {
      if (command == "pushPurchaseReceipt")
        this.handlePushReceipt()
      else if (command == "pushAdvancePaymentRequisition")
        this.handlePushPaymentRequisition();

    },
    handlePushReceipt() {
      var id = this.order.id;

      if (!id)
        return;
      pushReceipt(id).then(res => {
        if (!res)
          return;
        this.$notify({
          title: "成功",
          message: "下推成功",
          type: "success",
          position: "bottom-right",
        });
      })
    },
    handleAddAdvanceItem() {
      let item = this.getAdvanceItemDefaultValue();

      this.$refs.advanceTable.insertAt(item, -1);
      this.order.advancePaymentItems.push(item);
    },
    handleDeleteAdvanceItem({ ids, rows }) {
      if (rows.length == 0)
        return;

      let xids = rows.map((data) => {
        return data._XID;
      });

      this.order.advancePaymentItems = this.order.advancePaymentItems.filter((item) => {
        return xids.indexOf(item._XID) < 0
      })
    },
    getAdvanceItemDefaultValue() {
      return {
        advancePaymentPercent: null,
        advancePaymentAmountFr: null,
        dueDate: null,
        expectedDate: null,
        advancePaymentId: null,
        advancePaymentNumber: null,
        paymentAmountFr: null
      }
    },
    handleChangePercent(row) {
      row.advancePaymentAmountFr = (row.advancePaymentPercent / 100 * this.order.totalAmountFr).toMoney();
    },
    handleAdvanceFooterData({ columns, data }) {
      let result = [];

      let subTotalRow = columns.map((column, _columnIndex) => {
        if (_columnIndex === 0) {
          return "";
        }

        if (_columnIndex === 1) {
          return "";
        }
        if (
          ![
            "advancePaymentAmountFr",
            "paymentAmountFr"
          ].includes(column.property)
        ) {
          return "";
        }

        let total = 0;
        data.forEach((item) => {
          if (item[column.property]) total = total + +item[column.property];
        });
        return total.toMoney();
      });

      result.push(subTotalRow);
      return result;
    },
    handlePushPaymentRequisition() {
      pushPaymentRequisition(this.order.id).then(res => {
        this.$notify({
          title: "成功",
          message: "下推成功",
          type: "success",
          position: "bottom-right",
        });
      })
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.getData();
    });
  },
  computed: {
    id() {
      return this.$route.query.id;
    },
    readonly() {
      return this.order.status != 1 && this.order.status != 2;
    },
  },
  watch: {},
};
</script>
<style scoped></style>